package com.cory.admin.sys.controller.admin;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.beust.jcommander.internal.Lists;
import com.cory.admin.sys.controller.AdminController;
import com.cory.admin.sys.domain.entity.SysFile;
import com.cory.admin.sys.service.SysFileService;
import com.cory.boot.component.uploader.UploaderUtils;
import com.cory.boot.domain.bean.Result;
import com.google.common.collect.ImmutableMap;

/**
 * @author xiongcong
 * @date 2022-08-25
 */
@Controller
@RequestMapping("admin/sys/file")
public class SysFileController extends AdminController {
    @Autowired
    private SysFileService sysFileService;

    @RequestMapping("listByIds")
    @ResponseBody
    public Result<?> listByIds(String ids) {
        List<Integer> idList = Arrays.asList(ids.split(",")).stream().filter(item -> StringUtils.isNotBlank(item))
            .map(item -> Integer.valueOf(item)).collect(Collectors.toList());
        
        List<SysFile> files = sysFileService.getByIds(idList);
        List<Object> ret = Lists.newArrayList();
        files.forEach(i -> {
            ret.add(ImmutableMap.of("id", i.getId(), "fileId", i.getFileId(), "fileName", i.getFileName(), "fileUrl", UploaderUtils.getUrl(i.getFileId())));
        });
        
        return Result.success("ok", ret);
    }
    
    @RequestMapping("save")
    @ResponseBody
    public Result<?> save(@RequestBody SysFile file) {
        assertNotNull(file);
        assertNotNull(file.getFileId(), file.getFileName());
        sysFileService.save(file);
        
        return Result.success("", file.getId());
    }
}
